using SG3L_RAG.Application.Interfaces;
using Microsoft.Extensions.Configuration;
using System.Text;
using System.Text.Json;

namespace SG3L_RAG.Application.Services
{
    public class DeepSeekAIService : IAIService
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiKey;
        private readonly string _baseUrl;

        public DeepSeekAIService(HttpClient httpClient, IConfiguration configuration)
        {
            _httpClient = httpClient;
            // 从配置文件中读取API密钥和基础URL
            _apiKey = configuration["DeepSeek:ApiKey"] ?? 
                     Environment.GetEnvironmentVariable("DEEPSEEK_API_KEY") ?? 
                     throw new InvalidOperationException("DeepSeek API密钥未配置。请在appsettings.json中设置DeepSeek:ApiKey或设置DEEPSEEK_API_KEY环境变量。");
            
            _baseUrl = configuration["DeepSeek:BaseUrl"] ?? "https://api.deepseek.com/v1";
            
            _httpClient.DefaultRequestHeaders.Clear();
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
        }

        public async Task<string> GenerateAnswerAsync(string question, List<string> contexts)
        {
            try
            {
                string systemPrompt;
                string userPrompt;

                if (contexts == null || !contexts.Any() || contexts.All(string.IsNullOrWhiteSpace))
                {
                    // 没有上下文时的通用问答
                    systemPrompt = @"你是一个专业的AI助手，能够回答各种问题。
请遵循以下原则：
1. 提供准确、有用的信息
2. 回答要简洁明了
3. 使用中文回答
4. 如果不确定答案，请诚实说明";

                    userPrompt = question;
                }
                else
                {
                    // 基于上下文的RAG问答
                    systemPrompt = @"你是一个专业的AI助手，能够基于提供的文档内容回答用户问题。
请遵循以下原则：
1. 仅基于提供的上下文内容回答问题
2. 如果上下文中没有相关信息，请明确说明
3. 回答要准确、简洁、有条理
4. 可以适当引用原文内容来支持你的回答
5. 使用中文回答";

                    var contextText = string.Join("\n\n", contexts);
                    
                    userPrompt = $@"上下文信息：
{contextText}

用户问题：{question}

请基于以上上下文信息回答用户问题。";
                }

                var requestBody = new
                {
                    model = "deepseek-chat",
                    messages = new[]
                    {
                        new { role = "system", content = systemPrompt },
                        new { role = "user", content = userPrompt }
                    },
                    temperature = 0.7,
                    max_tokens = 2048,
                    stream = false
                };

                var json = JsonSerializer.Serialize(requestBody);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{_baseUrl}/chat/completions", content);
                
                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new HttpRequestException($"DeepSeek API请求失败: {response.StatusCode}, {errorContent}");
                }

                var responseContent = await response.Content.ReadAsStringAsync();
                
                var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

                var answer = responseData
                    .GetProperty("choices")[0]
                    .GetProperty("message")
                    .GetProperty("content")
                    .GetString();

                return answer ?? "抱歉，我无法生成回答。";
            }
            catch (Exception ex)
            {
                throw new Exception($"DeepSeek API调用失败: {ex.Message}", ex);
            }
        }

        public async Task<float[]> GenerateEmbeddingAsync(string text)
        {
            try
            {
                var requestBody = new
                {
                    model = "text-embedding-ada-002", // DeepSeek兼容OpenAI格式
                    input = text
                };

                var json = JsonSerializer.Serialize(requestBody);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{_baseUrl}/embeddings", content);
                
                if (!response.IsSuccessStatusCode)
                {
                    // 如果DeepSeek不支持embedding，使用简单的文本向量化
                    return GenerateSimpleEmbedding(text);
                }

                var responseContent = await response.Content.ReadAsStringAsync();
                var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

                var embedding = responseData
                    .GetProperty("data")[0]
                    .GetProperty("embedding")
                    .EnumerateArray()
                    .Select(x => (float)x.GetDouble())
                    .ToArray();

                return embedding;
            }
            catch (Exception)
            {
                // 如果API调用失败，使用简单的向量化方法
                return GenerateSimpleEmbedding(text);
            }
        }

        public async Task<string> SummarizeDocumentAsync(string content)
        {
            try
            {
                var systemPrompt = "你是一个专业的文档摘要助手。请为提供的文档内容生成简洁、准确的摘要。摘要应该包含文档的主要观点和关键信息。";

                var userPrompt = $"请为以下文档内容生成摘要：\n\n{content}";

                var requestBody = new
                {
                    model = "deepseek-chat",
                    messages = new[]
                    {
                        new { role = "system", content = systemPrompt },
                        new { role = "user", content = userPrompt }
                    },
                    temperature = 0.3,
                    max_tokens = 512
                };

                var json = JsonSerializer.Serialize(requestBody);
                var requestContent = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{_baseUrl}/chat/completions", requestContent);
                
                if (!response.IsSuccessStatusCode)
                {
                    return "无法生成文档摘要";
                }

                var responseContent = await response.Content.ReadAsStringAsync();
                var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

                var summary = responseData
                    .GetProperty("choices")[0]
                    .GetProperty("message")
                    .GetProperty("content")
                    .GetString();

                return summary ?? "无法生成文档摘要";
            }
            catch (Exception ex)
            {
                throw new Exception($"文档摘要生成失败: {ex.Message}", ex);
            }
        }

        public async Task<List<string>> ExtractKeywordsAsync(string text)
        {
            try
            {
                var systemPrompt = "你是一个关键词提取专家。请从提供的文本中提取5-10个最重要的关键词或关键短语。返回格式为用逗号分隔的关键词列表。";

                var userPrompt = $"请从以下文本中提取关键词：\n\n{text}";

                var requestBody = new
                {
                    model = "deepseek-chat",
                    messages = new[]
                    {
                        new { role = "system", content = systemPrompt },
                        new { role = "user", content = userPrompt }
                    },
                    temperature = 0.2,
                    max_tokens = 256
                };

                var json = JsonSerializer.Serialize(requestBody);
                var requestContent = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{_baseUrl}/chat/completions", requestContent);
                
                if (!response.IsSuccessStatusCode)
                {
                    return new List<string>();
                }

                var responseContent = await response.Content.ReadAsStringAsync();
                var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

                var keywordsText = responseData
                    .GetProperty("choices")[0]
                    .GetProperty("message")
                    .GetProperty("content")
                    .GetString();

                if (string.IsNullOrEmpty(keywordsText))
                    return new List<string>();

                var keywords = keywordsText
                    .Split(',', '，', '\n')
                    .Select(k => k.Trim())
                    .Where(k => !string.IsNullOrEmpty(k))
                    .Take(10)
                    .ToList();

                return keywords;
            }
            catch (Exception)
            {
                return new List<string>();
            }
        }

        private float[] GenerateSimpleEmbedding(string text)
        {
            // 简单的文本向量化方法（用于fallback）
            var random = new Random(text.GetHashCode());
            var embedding = new float[768]; // 标准embedding维度
            
            for (int i = 0; i < embedding.Length; i++)
            {
                embedding[i] = (float)(random.NextDouble() * 2 - 1); // -1到1之间的随机数
            }
            
            // 归一化
            var norm = Math.Sqrt(embedding.Sum(x => x * x));
            for (int i = 0; i < embedding.Length; i++)
            {
                embedding[i] = (float)(embedding[i] / norm);
            }
            
            return embedding;
        }
    }
}
